<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";

// 定义表单数据类型
interface PasswordForm {
  username: string;
  password: string;
}

interface SavedUserInfo {
  username: string;
  password: string;
}

// 定义props
defineProps<{
  loading: boolean;
}>();

// 定义emits
const emit = defineEmits<{
  (e: "login", formData: PasswordForm, remember: boolean): void;
}>();

// 表单引用
const formRef = ref<FormInstance | null>(null);

// 表单数据
const form = reactive<PasswordForm>({
  username: "",
  password: "",
});

// 状态管理
const showPassword = ref<boolean>(false);
const rememberPassword = ref<boolean>(false);

// 验证规则
const rules: FormRules = {
  username: [
    {
      required: true,
      message: "请输入邮箱/手机号",
      trigger: "blur",
    },
    {
      validator: (_rule, value, callback) => {
        // 验证手机号或邮箱格式
        const phoneReg = /^1[3-9]\d{9}$/;
        const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

        if (value && !phoneReg.test(value) && !emailReg.test(value)) {
          callback(new Error("请输入正确的手机号或邮箱"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      min: 6,
      max: 20,
      message: "密码长度在 6 到 20 个字符",
      trigger: "blur",
    },
  ],
};

// 页面加载时检查是否有记住的密码
onMounted(() => {
  const savedUserInfo = localStorage.getItem("savedUserInfo");
  if (savedUserInfo) {
    try {
      const parsedInfo: SavedUserInfo = JSON.parse(savedUserInfo);
      form.username = parsedInfo.username;
      form.password = parsedInfo.password;
      rememberPassword.value = true;
    } catch (error) {
      console.error("Failed to parse saved user info:", error);
      localStorage.removeItem("savedUserInfo");
    }
  }
});

// 处理登录
const handleLogin = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();
    // 触发登录事件
    emit("login", { ...form }, rememberPassword.value);
  } catch (error) {
    console.log("表单验证失败", error);
  }
};

// 暴露清除验证方法
const clearValidate = () => {
  formRef.value?.clearValidate();
};

defineExpose({
  clearValidate,
});
</script>

<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    class="login-form"
    autocomplete="off"
  >
    <el-form-item prop="username">
      <el-input
        v-model="form.username"
        placeholder="请输入邮箱/手机号"
        prefix-icon="User"
        clearable
      />
    </el-form-item>

    <el-form-item prop="password">
      <el-input
        v-model="form.password"
        type="password"
        placeholder="请输入密码"
        prefix-icon="Lock"
        :show-password="showPassword"
        @click:suffix="showPassword = !showPassword"
      />
    </el-form-item>

    <div class="form-actions">
      <el-checkbox v-model="rememberPassword" class="remember-checkbox">
        记住密码
      </el-checkbox>
      <el-link type="primary" class="forgot-link">忘记密码?</el-link>
    </div>

    <el-form-item>
      <el-button
        type="primary"
        class="login-btn"
        :loading="loading"
        @click="handleLogin"
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
@use "../styles/variables.scss" as vars;

.login-form {
  width: 100%;
  margin-top: 10px;
  .el-form-item {
    margin-bottom: 20px;
    .el-input {
      height: vars.$input-height;
      .el-input__wrapper {
        border-radius: vars.$radius;
      }
    }
  }
  .form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .remember-checkbox {
      font-size: 14px;
      color: vars.$light-text-color;
    }
    .forgot-link {
      font-size: 14px;
    }
  }
  .login-btn {
    width: 100%;
    height: vars.$btn-height;
    font-size: 16px;
    border-radius: vars.$radius;
  }
}
</style>
